package com.example.asd.puzzle;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.List;

import puzzle.Puzzle;

public class RoomWaitingActivity extends AppCompatActivity {
    private final String TAG="TAG";
    public static String str_roomName,str_roomOwner,str_server,str_myIP;
    private ListView listView;
    private LinearLayout linearLayout;
    private Button bt_dropRoom,bt_startGame;
    private TextView tv_roomName,tv_roomOwner;
    private List<String> strs_members=new ArrayList<>();
    private ArrayAdapter arrayAdapter;
    private Handler handler=new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.arg1){
                case 0://Toast
                    Toast.makeText(RoomWaitingActivity.this,msg.obj.toString(),Toast.LENGTH_SHORT).show();
                    break;
                case 1://Update members in room
                    try {
                        JSONObject room=(JSONObject)msg.obj;
                        str_roomName =room.getString("Name");
                        tv_roomName.setText("房间名："+str_roomName);
                        str_roomOwner=room.getString("Owner");
                        tv_roomOwner.setText("房主："+str_roomOwner);
                        JSONArray array=room.getJSONArray("Members");
                        strs_members.clear();
                        for(int i=0;i<array.length();i++){
                            strs_members.add(array.getString(i));
                        }
                        arrayAdapter.notifyDataSetChanged();
                        if (str_roomOwner.equals(str_myIP)){
                            linearLayout.setVisibility(View.VISIBLE);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case 2:// startGame
                    if (!str_roomOwner.equals(str_myIP)) {
                        Intent intent = new Intent(RoomWaitingActivity.this, GameActivity.class);
                        intent.putExtra("roomName", str_roomName);
                        startActivity(intent);
                        finish();
                    }
                    break;
                case 3:// dropRoom
                    finish();
                    break;
            }
        }
    };
    private PushService.MyBinder binder;
    private OnMsgReceivedListener listener=new OnMsgReceivedListener() {
        @Override
        public void onMsgReceived(JSONObject str) {
            try {
                String state=str.getString("State");
                if (state.equals("joinRoom")||state.equals("leaveRoom")){
                    apis_getRoomInfo();
                }else if (state.equals("startGame")){
                    Message m=new Message();
                    m.arg1=2;
                    handler.sendMessage(m);
                }else if (state.equals("dropRoom")){
                    Message m=new Message();
                    m.arg1=3;
                    handler.sendMessage(m);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void toastMe(String str) {
            toastMe(str);
        }
    };
    private ServiceConnection sc=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            binder=(PushService.MyBinder)iBinder;
            binder.setListener(listener);
        }
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        if (binder!=null)
            binder.setListener(listener);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_room_waiting);
        Intent intent=getIntent();
        str_roomName =intent.getStringExtra("roomName");
        str_server=MainActivity.str_server;
        str_myIP=MainActivity.str_myip;
        initUI();
        apis_getRoomInfo();
        pushCons();
    }

    private void pushCons() {
        Intent intent=new Intent(RoomWaitingActivity.this,PushService.class);
        bindService(intent,sc,BIND_AUTO_CREATE);
    }

    private void initUI() {
        tv_roomName=findViewById(R.id.wait_tv_roomName);
        tv_roomOwner=findViewById(R.id.wait_tv_owner);
        listView=findViewById(R.id.wait_lv_members);
        linearLayout=findViewById(R.id.wait_ly_owner);
        bt_dropRoom=findViewById(R.id.wait_bt_dropRoom);
        bt_startGame=findViewById(R.id.wait_bt_startGame);

        arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_expandable_list_item_1,strs_members);
        listView.setAdapter(arrayAdapter);
        bt_dropRoom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                apis_dropRoom();
            }
        });
        bt_startGame.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(RoomWaitingActivity.this,GameActivity.class);
                intent.putExtra("roomName",str_roomName);
                startActivity(intent);
                finish();
            }
        });
    }



    private void apis_dropRoom() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject po=new JSONObject();
                    po.put("Info", str_roomName);
                    String str= Puzzle.doRequest("http://"+str_server+":8080/apis/droproom",po.toString());
                    JSONObject o=(JSONObject)(new JSONTokener(str).nextValue());
                    if (o.getString("State").toString().equals("OK")) {
                        Message msg=new Message();
                        msg.arg1=3;
                        handler.sendMessage(msg);
                    }else {
                        toastMe(o.getString("Info"));
                        Log.d(TAG, "run: drop room failed "+str);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void apis_leaveRoom(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject po=new JSONObject();
                    po.put("Info", str_roomName);
                    String str= Puzzle.doRequest("http://"+str_server+":8080/apis/leaveroom",po.toString());
                    JSONObject o=(JSONObject)(new JSONTokener(str).nextValue());
                    if (o.getString("State").toString().equals("OK")) {
                        Log.d(TAG, "run: leaving room succeed");
                    }else {
                        Log.d(TAG, "run: leaving room failed "+str);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void apis_getRoomInfo(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    JSONObject po=new JSONObject();
                    po.put("Info",str_roomName);
                    Log.d(TAG, "run: getRoomInfo sent :"+po.toString());
                    String str=Puzzle.doRequest("http://"+str_server+":8080/apis/getroominfo",po.toString());
                    Log.d(TAG, "run: getRoomInfo :"+str);
                    JSONObject o=(JSONObject)(new JSONTokener(str).nextValue());
                    if (o.getString("State").toString().equals("OK")){
                        JSONObject jsonArray=o.getJSONObject("Data");
                        Message message=new Message();
                        message.arg1=1;
                        message.obj=jsonArray;
                        handler.sendMessage(message);
                    }else{
                        Log.d(TAG, "run: getRoomList() failed :"+o.getString("Info").toString());
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        apis_leaveRoom();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(sc);
    }
    private void toastMe(String string) {
        Message msg=new Message();
        msg.arg1=0;
        msg.obj=string;
        handler.sendMessage(msg);
    }
}
